package com.inspur.edp.rule.dsl.core.function.json;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2025/2/19 16:28
 */
public class JsonDataUtils {

    private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static String getString(JsonNode node, String fieldName) {
        if (node == null) {
            return null;
        }
        JsonNode fieldNode = node.get(fieldName);
        if (fieldNode == null || fieldNode.isNull()) {
            return null;
        }
        return fieldNode.asText();
    }

    public static double getDouble(JsonNode node, String fieldName) {
        if (node == null) {
            return 0;
        }
        JsonNode fieldNode = node.get(fieldName);
        if (fieldNode == null) {
            return 0;
        }
        return fieldNode.asDouble();
    }

    public static boolean getBoolean(JsonNode node, String fieldName) {
        if (node == null) {
            return false;
        }
        JsonNode fieldNode = node.get(fieldName);
        if (fieldNode == null) {
            return false;
        }
        return fieldNode.asBoolean();
    }

    public static OffsetDateTime getDateTime(JsonNode node, String fieldName) {
        if (node == null) {
            return null;
        }
        String dateStr = node.get(fieldName).asText();
        LocalDateTime localDateTime = LocalDateTime.parse(dateStr, DATE_TIME_FORMAT);
        OffsetDateTime offsetDateTime = localDateTime.atZone(ZoneId.systemDefault()).toOffsetDateTime();
        return offsetDateTime;
    }

    public static OffsetDateTime getDate(JsonNode node, String fieldName) {
        if (node == null) {
            return null;
        }
        String dateStr = node.get(fieldName).asText();
        LocalDate localDate = LocalDate.parse(dateStr, DATE_FORMAT);
        return localDate.atStartOfDay(ZoneId.systemDefault())
                .toOffsetDateTime();
    }

    public static ObjectNode getObject(JsonNode node, String fieldName) {
        if (node == null) {
            return null;
        }
        return (ObjectNode) node.get(fieldName);
    }

    public static ArrayNode getArray(JsonNode node, String fieldName) {
        if (node == null) {
            return null;
        }
        return (ArrayNode) node.get(fieldName);
    }

}
